﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetMicro.Core.Extensions;
using NetMicro.EventBus.Extensions;
using NetMicro.EventBus.Messages;
using RabbitMQ.Client;
using System;
using System.Threading.Tasks;

namespace NetMicro.EventBus.RabbitMQ
{
    /// <summary>
    /// 消息发送处理类
    /// </summary>
    public class RabbitMQMessageSender : IMessageSender
    {

        public RabbitMQMessageSender(
            IOptionsMonitor<EventBusRabbitMQOptions> options,
            IChannelFactory channelFactory,
            ILogger<RabbitMQMessageSender> logger,
            IMessageSerializer messageSerializer)
        {
            Options = options;
            Logger = logger;
            MessageSerializer = messageSerializer;
            ChannelFactory = channelFactory;

        }

        private IOptionsMonitor<EventBusRabbitMQOptions> Options { get; }
        private IChannelFactory ChannelFactory { get; }
        private ILogger<RabbitMQMessageSender> Logger { get; }
        private IMessageSerializer MessageSerializer { get; }

        public async Task Send(MessageTransfer message)
        {

            var Channel = await ChannelFactory.GetChannelAsync();
            Channel.ConfirmSelect();
            // 交换机定义,类型topic
            Channel.ExchangeDeclare(Options.CurrentValue.Exchange, "topic", true);
            IBasicProperties basicProperties = Channel.CreateBasicProperties();
            basicProperties.MessageId = message.MsgId;
            // 启用消息持久化
            basicProperties.Persistent = true;
            Channel.BasicPublish(Options.CurrentValue.Exchange, message.EventName, basicProperties,
                MessageSerializer.SerializeToBytesE(message));
            Channel.WaitForConfirmsOrDie(TimeSpan.FromSeconds(5));
            Logger.LogDebug($"[EventBus-RabbitMQ] send msg success: {message.ToJson()}.");
        }


    }
}